//
//  CatMessageVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/22.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatMessageVController.h"
#import "CatMessageCell.h"
#import "CatMessageModel.h"
//#import "YKPirVedioPlayVC.h"
//#import "YKPirMuImageViewController.h"
@interface CatMessageVController ()<UITableViewDataSource,UITableViewDelegate>
{
    // cell圆角
    CGFloat cornerRadius;
    // cell尺寸
    CGRect bounds;
    
    FBDevicesList *devicesList;

}
@property(nonatomic,strong)UITableView *messageListTableview;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIImageView *no_message_view;
@property(nonatomic,strong)UILabel *no_message_label;
@end

@implementation CatMessageVController

- (void)viewDidLoad {
    [super viewDidLoad];
     // 初始化cell的圆角半径
     cornerRadius = 8.f;
     self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
     self.dataArray = [NSMutableArray array];
    [self setup];
    [self getdata];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(@available(iOS 15.0,*)){
       UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
       apperance.backgroundColor = [UIColor whiteColor];//设置背景色
       self.navigationController.navigationBar.standardAppearance = apperance;
       self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
   
   self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
}

- (void)getdata
{
    
    devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    [self.dataArray removeAllObjects];
    
    [SVProgressHUD show];
    //默认获取三天内的消息
    long long startTime =  [[Tooles dateToUnixTime:[NSDate date]] longLongValue] - 86399000*devicesList.default_rollover_day;
    long long endTime = startTime + 86399000*(devicesList.default_rollover_day + 1);
    if (self.tag == 1) {
        
        [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework getCatFeedRecordWithBid:self.bid startTime:startTime end_time:endTime] errorHint:^(id errorData) {
            NSLog(@"获取喂食记录-->%@",errorData);
            self.no_message_view.hidden = NO;
            self.no_message_label.hidden = NO;
            [SVProgressHUD dismiss];
        } result:^(id value) {
            NSLog(@"获取喂食记录 ＝ %@",value);
            if ([[value objectForKey:@"code"] intValue] == 0) {
                NSMutableArray *alarm = [value objectForKey:@"data"];
                [self deal_feed_Data:alarm];
                
                if (alarm.count > 0) {
                    
                    NSDictionary *dict = [alarm firstObject];
                    FBDevicesList *stateInfo = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                    stateInfo.last_see_record = [[dict objectForKey:@"createTime"] longLongValue];
                    [stateInfo bg_saveOrUpdate];
                }
                
                
            }else{
                [SVProgressHUD dismiss];
                self.no_message_view.hidden = NO;
                self.no_message_label.hidden = NO;
            }
        }];
        
    }else{
  
        [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework getE1proLockAlarmdWithLockid:self.bid startTime:startTime end_time:endTime offset:0 limit:0] errorHint:^(id errorData) {
            NSLog(@"获取警告数量失败-->%@",errorData);
             self.no_message_view.hidden = NO;
             self.no_message_label.hidden = NO;
            [SVProgressHUD dismiss];
        } result:^(id value) {
            NSLog(@"获取警告数量 ＝ %@",value);
            if ([[value objectForKey:@"code"] intValue] == 0) {
                NSMutableArray *alarm = [value objectForKey:@"list"];
                [self dealData:alarm];
                
                if (alarm.count > 0) {
                     NSDictionary *dict = [alarm firstObject];
                     FBDevicesList *stateInfo = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                     stateInfo.last_see_alarm = [[dict objectForKey:@"time"] longLongValue];
                    [stateInfo bg_saveOrUpdate];
                }
                
            }else{
                [SVProgressHUD dismiss];
                self.no_message_view.hidden = NO;
                self.no_message_label.hidden = NO;
            }
        }];
    }
}

     

- (UIImageView*)no_message_view
{
    if (!_no_message_view) {
         _no_message_view = [[UIImageView alloc]init];
        [self.view addSubview:_no_message_view];
        [_no_message_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.mas_equalTo(205);
            make.height.mas_equalTo(140);
            make.top.equalTo(self.view.mas_top).offset(100+[UIDevice dev_navigationFullHeight]);
        }];
        _no_message_view.image = [UIImage imageNamed:@"cat_message_none"];
    }
    return _no_message_view;
}

- (UILabel*)no_message_label
{
    if (!_no_message_label) {
         _no_message_label = [[UILabel alloc]init];
         _no_message_label.userInteractionEnabled = YES;
         _no_message_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
         _no_message_label.textColor =[HexChangeRGB colorWithHexString:@"#999999"];
         _no_message_label.textAlignment = NSTextAlignmentCenter;
        [_no_message_label sizeToFit];
        [self.view addSubview:_no_message_label];
        [_no_message_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.no_message_view.mas_bottom).offset(10);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
        _no_message_label.text = NSLocalizedString(@"暂无消息哦～", nil);
    }
    return _no_message_label;
}

     
- (void)setup
{
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    
    UIButton *titlebuttton = [UIButton buttonWithType:UIButtonTypeCustom];
     titlebuttton.frame = CGRectMake(0,0,40,80);
     titlebuttton.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [titlebuttton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    if (self.tag == 1) {
        [titlebuttton setTitle:NSLocalizedString(@"喂食记录", nil) forState:UIControlStateNormal];
    }else{
        [titlebuttton setTitle:NSLocalizedString(@"告警消息", nil) forState:UIControlStateNormal];
    }
   self.navigationItem.titleView = titlebuttton;
    
}

- (void)selected_index:(NSInteger)index
{
    if (self.tag == index) {
        return;
    }
    self.tag = index;
    switch (index) {
        case 1:
        {
            [self getdata];
        }
            break;
        case 2:
        {
            [self getdata];
        }
            break;
        default:
            break;
    }
    
}



- (void)selectLeftActionClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealData:(NSMutableArray*)alarm
{
    /*
     {
     alarm = 102;
     "create_time" = 1679464769000;
     fid = "";
     "lock_aid" = f28ca7e402e45255ddadb37f18b4f041;
     "lock_id" = a4c78e8f07f78633240b0190f28ca7e4;
     pid = "";
     time = 1679464769000;
     }
     */
    //获取有几天的数据
    NSMutableArray *arry = [NSMutableArray array];
    for (NSDictionary *dict in alarm) {
        NSString *time = [dict objectForKey:@"time"];
        NSString *tmme2 = [Tooles timeToStrTime:time]; //将时间划分为一整天
        if(![arry containsObject:tmme2]){
            [arry addObject:tmme2];
        }
    }
    
    
    // 组内排序
    NSArray *sortArray = [arry sortedArrayUsingComparator:^NSComparisonResult(NSString *list1, NSString *list2) {
        if ([list1 longLongValue] < [list2 longLongValue]) {
            return NSOrderedDescending;//降序
        }else{
            return NSOrderedAscending;//升序
        }
    }];
    
    // 将同一天一天的数据放入同一数组
    for (NSString *time in sortArray) {
        NSMutableArray *ModelArray = [NSMutableArray array];
        CatMessageModel *model = [[CatMessageModel alloc]initWithTime:time type:[time intValue]];
        model.isheader = YES;
        [ModelArray addObject:model];
        for (NSDictionary *dict in alarm) {
            NSString *time3 = [dict objectForKey:@"time"];
            NSString *tmme2 = [Tooles timeToStrTime:time3];
            if([time isEqualToString:tmme2]){
                CatMessageModel *model2 = [[CatMessageModel alloc]initWithTime:[dict objectForKey:@"time"] type:[[dict objectForKey:@"alarm"] intValue]];
                [ModelArray addObject:model2];
            }
        }
        [self.dataArray addObject:ModelArray];
    }
    [SVProgressHUD dismiss];
    
    if (self.dataArray.count) {
        self.no_message_view.hidden = YES;
        self.no_message_label.hidden = YES;
        self.messageListTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
       [self.messageListTableview reloadData];
       
    }else{
        
        if (_messageListTableview) {
           [_messageListTableview removeFromSuperview];
            _messageListTableview = nil;
        }
        self.no_message_view.hidden = NO;
        self.no_message_label.hidden = NO;
       
    }
    
}


- (void)deal_feed_Data:(NSMutableArray*)alarm
{
    /*
     {
         context = "\U5582\U98df\U4e8610\U4efd\U7cae\U98df";
         createTime = "2024-06-05 16:31:29";
         deviceId = a454c67109863917204512809bdd85c2;
         id = d67d87d1453e4c289ac375f0af2c081b;
         type = 1;
         userId = b869c6c6072ae929046e05f054b6b1dd;
   }
      */
    //获取有几天的数据
    NSMutableArray *arry = [NSMutableArray array];
    for (NSDictionary *dict in alarm) {
        NSString *time = [dict objectForKey:@"createTime"];
        NSString *tmme2 = [Tooles timeToStrTime:time]; //将时间划分为一整天
        if(![arry containsObject:tmme2]){
            [arry addObject:tmme2];
        }
    }
    
    
    // 组内排序
    NSArray *sortArray = [arry sortedArrayUsingComparator:^NSComparisonResult(NSString *list1, NSString *list2) {
        if ([list1 longLongValue] < [list2 longLongValue]) {
            return NSOrderedDescending;//降序
        }else{
            return NSOrderedAscending;//升序
        }
    }];
    
    // 将同一天一天的数据放入同一数组
    for (NSString *time in sortArray) {
        NSMutableArray *ModelArray = [NSMutableArray array];
         CatMessageModel *model = [[CatMessageModel alloc]initWithTime:time type:[time intValue]];
         model.isheader = YES;
         model.message_type = 1;
        [ModelArray addObject:model];
        for (NSDictionary *dict in alarm) {
            NSString *time3 = [dict objectForKey:@"createTime"];
            NSString *tmme2 = [Tooles timeToStrTime:time3];
            if([time isEqualToString:tmme2]){
               CatMessageModel *model2 = [[CatMessageModel alloc]initWithTime:[dict objectForKey:@"createTime"] type:[[dict objectForKey:@"type"] intValue]];
               model2.title = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"number"] intValue]];
               model2.message_type = 1;
               model2.bid = self.bid;
               model2.category = [[dict objectForKey:@"category"] intValue];
               model2.originFileId = [dict objectForKey:@"originFileId"];
               model2.previewFileId = [dict objectForKey:@"previewFileId"];
              [ModelArray addObject:model2];
            }
        }
        [self.dataArray addObject:ModelArray];
    }
    [SVProgressHUD dismiss];
    if (self.dataArray.count > 0) {
        self.no_message_view.hidden = YES;
        self.no_message_label.hidden = YES;
        self.messageListTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
       [self.messageListTableview reloadData];
    }else{
        if (_messageListTableview) {
           [_messageListTableview removeFromSuperview];
            _messageListTableview = nil;
        }
        self.no_message_view.hidden = NO;
        self.no_message_label.hidden = NO;
    }
    
}


- (UITableView*)messageListTableview
{
     if(!_messageListTableview){
         _messageListTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         _messageListTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
         _messageListTableview.dataSource= self;
         _messageListTableview.delegate = self;
         _messageListTableview.backgroundColor =  [HexChangeRGB colorWithHexString:@"#F5F5F5"];
         UIView *view = [[UIView alloc] init];
         view.frame = CGRectMake(0, 0, 0 , 0.01);
         _messageListTableview.tableHeaderView = view;
        [_messageListTableview registerClass:[CatMessageCell class] forCellReuseIdentifier:@"CatMessageCell"];
         _messageListTableview.rowHeight = 44;
        [self.view addSubview:_messageListTableview];
        [_messageListTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(14);
            make.right.equalTo(self.view.mas_right).offset(-14);
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _messageListTableview;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *array = self.dataArray[section];
    return array.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
  
    CatMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatMessageCell" forIndexPath:indexPath];
    
    if (indexPath.section < self.dataArray.count) {
        NSMutableArray *array = self.dataArray[indexPath.section];
        CatMessageModel *model = array[indexPath.row];
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        cell.camera_id = devicesList.camera_id;
        if(indexPath.row == array.count -1){
            cell.line2.hidden = YES;
        }else{
            cell.line2.hidden = NO;
            if(indexPath.row == 1){
                cell.line1.hidden = YES;
            }else{
                cell.line1.hidden = NO;
            }
        }
        
        if (array.count == 2) {
            cell.line1.hidden = YES;
            cell.line2.hidden = YES;
        }
        
    }
   
    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0) {
        return;
    }
    
    NSMutableArray *array = self.dataArray[indexPath.section];
    CatMessageModel *model = array[indexPath.row];
    NSLog(@"model.fid == %@",model.originFileId);
    if (model.originFileId.length > 0) {
        
        if (model.category == 2) {
            
           
            NSURL *url = [YKBusinessFramework equesGetAlarmfileUrl:model.bid fid:model.originFileId context:@""];
            
            NSLog(@"视频的url == %@",url);
            
            
        }else{
        

            NSURL *url = [YKBusinessFramework equesGetAlarmfileUrl:model.bid fid:model.originFileId context:@""];
            NSLog(@"图片的url == %@",url);
        }
    
    }

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return  30;
    }else{
        NSMutableArray *array = self.dataArray[indexPath.section];
        CatMessageModel *model = array[indexPath.row];
        if (model.previewFileId.length > 0) {
            return  80;
        }else{
            return  40;
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
     return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
     return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
     return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor whiteColor];
     return view;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 0.cell背景透明，否则不会出现圆角效果
    cell.backgroundColor = [UIColor clearColor];

    // 原因如下：
    // 之所以设置为透明，是因为cell背景色backGroundColor是直接设置在UITableViewCell上面的，位于cell的第四层
    // backGroundView是在UITableViewCell之上的，也就是位于cell的第三层
    // 我们所要做的操作是在backGroundView上，也就是第三层
    // 第三层会挡住第四层，如果第四层设置了颜色，那么将来cell的圆角部分会露出第四层的颜色，也就是背景色
    // 所以，必须设置cell的背景色为透明色！
    // 另外:
    // 第二层是UITableViewCellContentView，默认就是透明的，无需设置
    // 第一层是UITableViewLabel，也就是cell.textLabel
    
    // 1.创建path,保存绘制的路径
    CGMutablePathRef pathRef = CGPathCreateMutable();
    pathRef = [self drawPathRef:pathRef forCell:cell atIndexPath:indexPath];
    
    // 2.创建layer,渲染效果
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    [self renderCornerRadiusLayer:layer withPathRef:pathRef toCell:cell];
}



#pragma mark - private method
- (CGMutablePathRef)drawPathRef:(CGMutablePathRef)pathRef forCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // cell的bounds
    bounds = cell.bounds;
    
    if (indexPath.row == 0 && indexPath.row == [self.messageListTableview numberOfRowsInSection:indexPath.section] - 1) {
        // 1.既是第一行又是最后一行
        // 1.1.底端中点 -> cell左下角
        CGPathMoveToPoint(pathRef, nil, CGRectGetMidX(bounds), CGRectGetMaxY(bounds));
        // 1.2.左下角 -> 左端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMinX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 1.3.左上角 -> 顶端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        // 1.4.cell右上角 -> 右端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 1.5.cell右下角 -> 底端中点
        CGPathAddArcToPoint(pathRef, nil,   CGRectGetMaxX(bounds), CGRectGetMaxY(bounds),CGRectGetMidX(bounds), CGRectGetMaxY(bounds),cornerRadius);
        
        return pathRef;
        
    } else if (indexPath.row == 0) {
        // 2.每组第一行cell
        // 2.1.起点： 左下角
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        // 2.2.cell左上角 -> 顶端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        // 2.3.cell右上角 -> 右端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 2.4.cell右下角
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
        // 绘制cell分隔线
        // addLine = YES;
        return pathRef;
        
    } else if (indexPath.row == [self.messageListTableview numberOfRowsInSection:indexPath.section] - 1) {
        // 3.每组最后一行cell
        // 3.1.初始起点为cell的左上角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
        // 3.2.cell左下角 -> 底端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        // 3.3.cell右下角 -> 右端中点
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 3.4.cell右上角
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
       
        return pathRef;
        
    }else if (indexPath.row != 0 && indexPath.row != [self.messageListTableview numberOfRowsInSection:indexPath.section] - 1) {
        // 4.每组的中间行
        CGPathAddRect(pathRef, nil, bounds);
        
        return pathRef;
    }
    return nil;
}

- (void)renderCornerRadiusLayer:(CAShapeLayer *)layer withPathRef:(CGMutablePathRef)pathRef toCell:(UITableViewCell *)cell {
    // 绘制完毕，路径信息赋值给layer
    layer.path = pathRef;
    // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
    CFRelease(pathRef);
    // 按照shape layer的path填充颜色，类似于渲染render
    layer.fillColor = [UIColor whiteColor].CGColor;
    
    // 创建和cell尺寸相同的view
    UIView *backView = [[UIView alloc] initWithFrame:bounds];
    // 添加layer给backView
    [backView.layer addSublayer:layer];
    // backView的颜色
    backView.backgroundColor = [UIColor clearColor];
    // 把backView添加给cell
    cell.backgroundView = backView;
}




@end
